package com.aaa.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsUtils;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    SuccessHandlerConfig successHandlerConfig;
    @Resource
    FailureHandlerConfig failureHandlerConfig;
    @Resource
    AccessDeniedHandlerConfig accessDeniedHandlerConfig;
    @Resource
    AuthenticationEntryPointConfig authenticationEntryPointConfig;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .csrf()
                .disable()
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .and()
//        super.configure(http);
        .formLogin()

                .loginPage("/login")

                // 登录处理路径：action=/login
                 //.loginProcessingUrl("/checkUser")
                // 默认成功路径：1.访问a  2.访问login.html
                 //.defaultSuccessUrl("/success.html")
                //.permitAll()
                // 成功 重定向路径
                //.successForwardUrl("/user/login")
                // 失败重定向路径
                //.failureForwardUrl("")
                // 失败路径
                // .failureUrl("/error.html").permitAll()
                // 用户名参数
                .usernameParameter("name")
                // 密码参数
                .passwordParameter("password")
//                // 认证成功处理器
                .successHandler(successHandlerConfig)
//                // 认证失败处理器
                .failureHandler(failureHandlerConfig)
                // 允许访问
                .permitAll()
                .and()
                // 所有请求必须进行认证
                .authorizeRequests()
                .antMatchers("/user/login")
                .permitAll()
                .anyRequest()
                //.authenticated()
                // 是否允许访问:根据rbacConfig对象中的hasAuthority方法的返回值判断是否允许访问，返回true可以访问，返回false
                .access("@rbacConfig.hasAuthority(authentication,request)")
                .and()
                // 异常处理
                //.exceptionHandling()
                // 认证成功，权限不足，访问被拒绝
                //.accessDeniedHandler(accessDeniedHandlerConfig)
                // 访问被拒绝：未认证
                //.authenticationEntryPoint(authenticationEntryPointConfig)
                //.and()
                // /logout
                .logout()//退出
                .permitAll()
                // 记住用户名密码
                // .rememberMe()
                // .alwaysRemember(true)
                .and()
                .csrf()
                .disable();
    }
    @Resource
    UserDetailsConfig userDetailsConfig;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 用户详细信息：会自动调用loadUserByUsername方法获取用户详细信息
        auth.userDetailsService(userDetailsConfig)
                // 密码编译器
                .passwordEncoder(passwordEncoder());
    }
//
    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String s = passwordEncoder.encode("123");
        System.out.println(s);
        System.out.println(passwordEncoder.encode("111"));
//        System.out.println(passwordEncoder.encode("222"));
    }
}
